package com.mmlc.utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/9/20 0020.
 */
public class ReflectToBeanUtils {
    public static  List reflectArrayToBean(Class currObject,List jsonSrc, int position){
        boolean exeOne = true;
        ArrayList arrayList = new ArrayList<>();
        for(int i=0;i<jsonSrc.size();i++){

            try {
                Object fromObj = jsonSrc.get(i);
                Class<?> fromClass = fromObj.getClass();
                Field[] fromFields = fromClass.getDeclaredFields();

                Object toObject = currObject.newInstance();
                arrayList.add(toObject);
                Field[] toFields = currObject.getDeclaredFields();
                //toObject 解析出key-field值
                if(exeOne){
                    exeOne = false;
                    getJsonKeyAndFieldKey(toObject,position);
                }

                //开始解析
                for (Field toField : toFields) {
                    toField.setAccessible(true);
                    String name = toField.getName();
                    String tmpName = keyMap.get(name);//类中
                    if(tmpName != null){
                        for(Field fromField : fromFields){
                            fromField.setAccessible(true);
                            if(tmpName.equals(fromField.getName())){
                                Object value =fromField.get(fromObj);
                                toField.set(toObject,value);
                                break;
                            }
                        }
                    }

                }

            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }

        return arrayList;
    }
    public static List<String> keys = new ArrayList<>();
    public static HashMap<String,String> keyMap = new HashMap<>();
    public static String objOrListName = "";
    private static HashMap<String, String> getJsonKeyAndFieldKey(Object testShopItemClass, int position) {
        String[] values = null;
        Class<?> tmpClass = testShopItemClass.getClass();
        keys.clear();
        keyMap.clear();
        objOrListName="";

        if (tmpClass.isAnnotationPresent(DataReflect.class)) {
            //获取注解对象
            Annotation annotation = tmpClass.getAnnotation(DataReflect.class);
            try {
                //获取注解@Table所对应的name
                Method method = DataReflect.class.getMethod("keyFiled");
                values = (String[]) method.invoke(annotation);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String str = values[position];
        String[] split = str.split(",");

        for(int i=0;i<split.length;i++){
            String s = split[i];

            String[] split1 = s.split("=");

          /*  if(i == 0){
                objOrListName = split1[0];
                continue;
            }*/

            keys.add(split1[1]);//field的key

            keyMap.put(split1[1],split1[0]);//json的key
        }
        return keyMap;
    }

    public static Object reflectJsonToObject(Class objClass, String json, int i) {
        //先获取映射表
        Object obj = null;
        try {
            obj = objClass.newInstance();

            getJsonKeyAndFieldKey(obj,0);

            JSONObject jsonObject = new JSONObject(json);
            if(!"null".equals(objOrListName)){
                jsonObject = jsonObject.getJSONObject(objOrListName);
            }

            for(int j=0;j<keys.size();j++){
                String jsonField = keyMap.get(keys.get(j));
                Object jsonData = null;
                Field declaredField = objClass.getDeclaredField(keys.get(j));
                String simpleName = declaredField.getType().getSimpleName();
                if("String".equals(simpleName)){
                     jsonData = jsonObject.optString(jsonField);
                }else if("Integer".equals(simpleName)){
                     jsonData = jsonObject.optInt(jsonField);
                }else if("Float".equals(simpleName)){
                     jsonData = jsonObject.optDouble(jsonField);
                }
                copyToField(obj,keys.get(j),jsonData);
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        return obj;
    }
    public static List reflectJsonToList(Class objClass, String json, int i) {
        ArrayList<Object> listBean = new ArrayList<>();
        //先获取映射表
        Object obj = null;
        try {
            obj = objClass.newInstance();

            getJsonKeyAndFieldKey(obj,0);

            JSONArray jsonArray = null;

            if("null".equals(objOrListName)){
                jsonArray = new JSONArray(json);
            }else{
                JSONObject jsonObject = new JSONObject(json);
                jsonArray = jsonObject.getJSONArray(objOrListName);
            }

            for(int j = 0;j<jsonArray.length();j++){

                JSONObject jsonObject = jsonArray.getJSONObject(j);
                Object tmpObj = objClass.newInstance();
                for(int k=0;k<keys.size();k++){
                    String jsonField = keyMap.get(keys.get(k));
                    Object jsonData = null;
                    Field declaredField = objClass.getDeclaredField(keys.get(k));
                    String simpleName = declaredField.getType().getSimpleName();
                    if("String".equals(simpleName)){
                        jsonData = jsonObject.optString(jsonField);
                    }else if("Integer".equals(simpleName)){
                        jsonData = jsonObject.optInt(jsonField);
                    }else if("Float".equals(simpleName)){
                        jsonData = jsonObject.optDouble(jsonField);
                    }

                    copyToField(tmpObj,keys.get(k),jsonData);
                }
                listBean.add(tmpObj);
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        return listBean;
    }

    public static List<String> objNameList = new ArrayList<>();
    public static HashMap<String,List<String>> objNameHash = new HashMap<>();
    public static List<String> arrayNameList = new ArrayList<>();
    public static Object reflectJsonToBean(Class objClass, String json, int pos) throws IllegalAccessException, InstantiationException {
        //"{}.=.{code=code,message=message}-[]data=.data{pay_name=payName}-[]data.[]ext_info=.data.extInfo{key=key,value=value}"
        /*String[] mapRules = getMapRule(objClass);
        if(mapRules == null || pos > mapRules.length){
            return null;
        }
        String mapRuleString = mapRules[pos];
        String[] split = mapRuleString.split("-");
        for(int i=0;i<split.length;i++){
            //去除前后的空格
            String trim = split[i].trim();
            if(trim.startsWith("[]")){
                int pos1 = trim.indexOf("{");
                String subS = trim.substring(1, pos1);
                if(subS.contains("=")){//是否包含了=
                    String[] split2 = subS.split("=");
                    String trim0 = split2[0].trim();
                    objNameList.add(trim0);
                    String trim1 = split2[1].trim();
                }else{
                    objNameList.add("currObj");
                }
            }else if(split[i].startsWith("{}")){
                
            }
        }*/

        //解析数据
        //创建对象
        objNameList.add(".");
        objNameList.add(".data");
        objNameList.add(".data.extInfo");
        Object obj = null;
        for(int j=0;j<objNameList.size();j++){
            if(objNameList.get(j) == "."){//当前对象
                obj = objClass.newInstance();
                break;
            }
        }
        if(obj == null){
            return null;
        }


        //对新对象中的成员再创建对象
        for(int j=0;j<objNameList.size();j++){
            String str = objNameList.get(j);
            String[] split1 = str.split("\\.");


            for(int g=1;g<split1.length;g++){

            }


            for(int k = 1;k<split1.length;k++){
                String s = split1[k];
                try {

                    Field field = obj.getClass().getField(s);
                    String s1 = field.getGenericType().toString();
                    
                    if(s1.startsWith(List.class.getCanonicalName())){
                        ArrayList<Object> list = new ArrayList<>();
                        s1 = s1.substring(s1.indexOf("<")+1, s1.indexOf(">"));
                        Object o = Class.forName(s1).newInstance();
                        field.setAccessible(true);
                        field.set(obj,list);
                    }



                   /* Field field1 = o.getClass().getField(split1[1]);
                    String s2 = field1.getGenericType().toString();*/
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }

            if(objNameList.get(j) == ""){//当前对象
                try {
                    obj = objClass.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

       /* else{
            try {
                Field field = objClass.getField(objNameList.get(j));
                String typeS = field.getGenericType().toString();
                Object tmpObj = Class.forName(typeS).newInstance();
                field.setAccessible(true);
                field.set(obj,tmpObj);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }



        ArrayList<Object> listBean = new ArrayList<>();
        //先获取映射表
        Object obj = null;
        try {
            obj = objClass.newInstance();

            getJsonKeyAndFieldKey(obj,0);

            JSONArray jsonArray = null;

            if("null".equals(objOrListName)){
                jsonArray = new JSONArray(json);
            }else{
                JSONObject jsonObject = new JSONObject(json);
                jsonArray = jsonObject.getJSONArray(objOrListName);
            }

            for(int j = 0;j<jsonArray.length();j++){

                JSONObject jsonObject = jsonArray.getJSONObject(j);
                Object tmpObj = objClass.newInstance();
                for(int k=0;k<keys.size();k++){
                    String jsonField = keyMap.get(keys.get(k));
                    Object jsonData = null;
                    Field declaredField = objClass.getDeclaredField(keys.get(k));
                    String simpleName = declaredField.getType().getSimpleName();
                    if("String".equals(simpleName)){
                        jsonData = jsonObject.optString(jsonField);
                    }else if("Integer".equals(simpleName)){
                        jsonData = jsonObject.optInt(jsonField);
                    }else if("Float".equals(simpleName)){
                        jsonData = jsonObject.optDouble(jsonField);
                    }

                    copyToField(tmpObj,keys.get(k),jsonData);
                }
                listBean.add(tmpObj);
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }*/

        return null;
    }

    private static String[] getMapRule(Class objClass) {
        if (objClass.isAnnotationPresent(DataReflect.class)) {
            //获取注解对象
            DataReflect annotation = (DataReflect) objClass.getAnnotation(DataReflect.class);
            return annotation.keyFiled();
        }
        return null;
    }

    private static void copyToField( Object obj, String field,Object jsonData) throws IllegalAccessException, NoSuchFieldException {
        Class<?> objClass = obj.getClass();
        Field objField = objClass.getDeclaredField(field);
        objField.setAccessible(true);
        objField.set(obj,jsonData);
    }

    public static class parseData{
        //HashMap
    }
}
